package com.smart.dao;
 
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.smart.model.Lead;
import com.smart.model.LeadCond;
import com.smart.util.CollectionUtil;

/**
 * 
 * @author Sunxin
 *
 */
 
@Repository
public class LeadDaoImpl extends BaseEntityDao<Lead, LeadCond, Long> implements LeadDao{

	@Override
	public Map<String, BigInteger> getLeadStat(String team, Date from, Date to) {
		String sql = "select status, count(*) as count from lead where team = :team and upd_time > :from and upd_time < :to group by status";
		SQLQuery query = super.getSession().createSQLQuery(sql);
		query.setParameter("team", team);
		query.setParameter("from", from);
		query.setParameter("to", to);
		List<Object[]> data = query.list();
		if(CollectionUtil.isEmpty(data)) {
			return null;
		}
		Map<String, BigInteger> map = new TreeMap<String, BigInteger>();
		for(Object[] row : data) {
			map.put((String)row[0], (BigInteger)row[1]);
		}
		return map;
	}

	@Override
	public Page<Lead> findByKeywords(LeadCond cond, String keywords) {
		keywords = "%" + keywords + "%";
		Criteria crit = super.getSession().createCriteria(Lead.class);
		crit.add(Restrictions.and(Restrictions.eq("team", cond.getTeam()),
				Restrictions.or(Restrictions.like("mobile", keywords), Restrictions.like("wechat", keywords), Restrictions.like("wechatName", keywords))));
		if(cond.getBeginCrtTime()!=null) {
			crit.add(Restrictions.gt("crtTime", cond.getBeginCrtTime()));
		}
		if(cond.getEndCrtTime()!=null) {
			crit.add(Restrictions.le("crtTime", cond.getEndCrtTime()));
		}
		return super.findPage(new PageRequest(), crit);
	}

}
